//
//  CLKeyedArchiver.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/17.
//

#import "CLKeyedArchiver.h"

@implementation CLKeyedArchiver
/// 归档文件
+ (void)archiver:(NSString *)folderName fileName:(NSString*)fileName object:(id)object {
    NSString *path = [NSString stringWithFormat:@"%@/%@/%@",HomePath,CL_READ_FOLDER_NAME,folderName];//CL_READ_DOCUMENT_DIRECTORY_PATH + "/\(DZM_READ_FOLDER_NAME)/\(folderName!)"
    
    if ([self creat_file:path]) { // 创建文件夹成功或者文件夹存在
        path = [path stringByAppendingFormat:@"/%@",fileName];
        [NSKeyedArchiver archiveRootObject:object toFile:path];
    }
}

/// 解档文件
+ (id)unarchiver:(NSString *)folderName fileName:(NSString*)fileName {
    NSString *path = [NSString stringWithFormat:@"%@/%@/%@/%@",HomePath,CL_READ_FOLDER_NAME,folderName,fileName];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

/// 清空归档文件
+ (BOOL)clear {
    NSString *path = [NSString stringWithFormat:@"%@/%@",HomePath,CL_READ_FOLDER_NAME];
    @try {
        [NSFileManager.defaultManager removeItemAtPath:path error:nil];
        return YES;
    } @catch (NSException *exception) {}
    return NO;
}

/// 是否存在归档文件
+ (BOOL)isExist:(NSString *)folderName fileName:(NSString *)fileName {
    NSString *path = [NSString stringWithFormat:@"%@/%@/%@",HomePath,CL_READ_FOLDER_NAME,folderName];
    if (!NULLString(fileName)) { path = [path stringByAppendingFormat:@"/%@",fileName]; }
    return [NSFileManager.defaultManager fileExistsAtPath:path];
}

/// 创建文件夹,如果存在则不创建
+ (BOOL)creat_file:(NSString *)path {
    NSFileManager *fileManager = NSFileManager.defaultManager;
    if ([fileManager fileExistsAtPath:path]) { return YES; }
    @try {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        return YES;
    } @catch (NSException *exception) {}
    return NO;
}
@end
